package com.pactera.asmp.server.common.websocket.webrtc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.utils.SpringUtil;
import com.pactera.asmp.server.entity.CameraInfoDTO;
import com.pactera.asmp.server.service.ICameraService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @ projectName: webRtc_Server @ package:
 * com.gientech.webrtc_server.controller @ className: WebRTCController @ author:
 * Carson @ description: @ date: 2023/5/17/017 11:37 @ version: 1.0
 */
@ServerEndpoint(value = "/ws/websocket/{id}/{requestType}")
@Controller
@Slf4j
public class WebRTCController {

    private ICameraService cameraService;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id,
            @PathParam(value = "requestType") String requestType) throws IOException {
        log.info("注册session用户 id：{}  mode={}", id, requestType);
        WebRTCSessionManager.setSession(id, requestType, session);
        Model model = new Model("response", "WebRTCServer", "", "id:" + id + " 注册成功", "true");
        session.getBasicRemote().sendText(JSON.toJSONString(model));
    }

    @OnClose
    public void onClose(Session session) {
        log.info("onClose");

        String cuid = WebRTCSessionManager.removeSession(session.getId());
        if (cuid != null) {
            this.cameraService().offlineCamera(new CameraInfoDTO() {
                {
                    setCuid(cuid);
                }
            });
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
//        log.info("客户端消息：{}", message);
        JSONObject jsonObject = JSON.parseObject(message);
        String to = jsonObject.getString("to");
        if (to == null || to.equals("")) {
            log.info("无有效目标用户id");
            Model model = new Model("response", "WebRTCServer", "", "无有效目标用户id", "false");
            model.setIsSuccess("false");
            session.getBasicRemote().sendText(JSON.toJSONString(model));
        } else {
            WebRTCSessionManager.sendMessage(to, jsonObject.toJSONString(), session);
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("webSocket Session：{} 错误:{} getCause:{}", session.getId(), throwable.getMessage(),
                throwable.getCause());
        // WebRTCSessionManager.removeSession(session.getId());
    }

    private ICameraService cameraService() {
        if (this.cameraService == null)
            this.cameraService = SpringUtil.getBean(ICameraService.class);
        return this.cameraService;
    }
}
